import { useParams } from '@/router/hooks';
import { connectorTypeReq } from '@/types/know/know';
import { Button, message, Input, Space, Splitter } from 'antd';
import {
  PlusOutlined,
  SearchOutlined,
  CloseOutlined,
  DownOutlined,
  UpOutlined,
} from '@ant-design/icons';
import ConnectorDeleteModal from './components/connectorDeleteModal';
import ConnectorAddModal from './components/connectorAddModal';

import { useCallback, useEffect, useRef, useState } from 'react';
import knowService from '@/api/services/knowService';
import '@/pages/know-gov/styles/know-gov.scss';
import React from 'react';
import datasetService from '@/api/services/knowService';
import type { TableColumnsType, TableProps } from 'antd';
import useWindowWidth from '@/hooks/event/use-window-width';
import { debounce, isArray } from 'lodash';
import { Ellipsis } from 'antd-mobile';
import PagesHeader from '@/components/pages-header';
import orgService from '@/api/services/orgService';
import { GetDatasetList } from '@/common/types';
import { DatasetType } from '@/common';
import Tables from '@/components/tables/tables';
import { ColumnFilterItem } from 'antd/es/table/interface';
import PaginationTable from '../../components/PaginationTableConnect';
import NotData from '@/components/NotData';
import { SvgIcon } from '@/components/icon';
import { Search } from '@/components/eai-design';
import { useRequest2 } from '@/hooks/use-request';
import TipDesc from '@/components/tipDesc/tipDesc';
type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];

interface DataType {
  name: string;
  age: number;
  address: string;
  createTime: string;
  dbConfig: [];
  description: string;
  latestSyncTime: string;
  progress: number;
  status: string;
  type: string;
  updateTime: string;
  urls: [];
  _id: string;
  act: string;
  cron: string;
  remainingTime: string;
}

interface ItemType {
  type: string;
  name: string;
  datasetId?: string;
  cron?: string;
  datasetCreateType?: string;
  datasetNameMetadata?: string;
  apiKey?: string;
  link: string;
  sql: string;
  urls: string[];
  databaseType: string;
  isdeep: boolean;
  updataTime?: string;
  clockTime?: string;
  depth?: string;
  feishuAppSecret?: string;
  feishuAppId?: string;
  forceSync?: boolean;
}

const Connector = () => {
  const { isPc } = useWindowWidth();

  const [showDel, setShowDel] = useState(false);
  const [showAdd, setShowAdd] = useState(false);
  const [title, setTitle] = useState('');
  const [searchText, setSearchText] = useState('');
  const [filtType, setFiltType] = useState('');

  const [refreshSimilarity, setRefreshSimilarity] = useState(0);

  const [connectorList, setConnectorList] = useState(null);

  const [onItem, setOnItem] = useState<ItemType>({});
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [treeData, setTreeData] = useState<GetDatasetList[]>([]);

  const [isErr, setIsErr] = useState('');

  const [dataList, setDataList] = useState([]);
  const dataListRef = useRef(dataList);
  const intervalRef = useRef<NodeJS.Timeout>();

  const { appId = '' } = useParams() as { appId: string };
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);

  // const [tableValues, setTableValue] = useState<connectorTypeReq[]>([]);
  const paginationConfig = {
    current: page,
    pageSize: pageSize,
    pageSizeOptions: undefined,
    total: total,
    onChange: (page: number, pageSize: number) => {
      setPage(page);
      setPageSize(pageSize);
    },
  };
  const [paginationTotal, setPagintionTotal] = useState(0);

  const typeTitle = {
    all: '全部类型',
    file: '文件',
    web: '网页',
    api: 'API',
    database: '数据库',
    feishu: '飞书',
  };
  const [datasetTypeFillter, setDatasetTypeFillter] = useState<ColumnFilterItem[]>([]);

  const filterDatasetTypeList = (obj: object) => {
    const result = [] as any;
    const counts: Record<DatasetType, string[]> = {
      all: [],
      file: [],
      web: [],
      api: [],
      database: [],
      feishu: [],
    };
    for (const [key, value] of Object.entries(obj)) {
      console.log(key, value, '=key, value');
      counts[value.type as DatasetType].push(key);
      counts.all.push(key);
    }
    Object.entries(counts).forEach(([type, keys], index) => {
      result.push({
        text: `${typeTitle[type]}(${keys.length})`,
        value: type,
      });
    });
    return result;
  };

  useEffect(() => {
    getDataset();
    getTableValue();
  }, [appId]);

  const { refresh: getTableValue, loading } = useRequest2(
    () => knowService.getConnectorList({ appId, page, pageSize, searchText }),
    {
      manual: false,
      refreshDeps: [appId, page, pageSize, searchText],
      debounceWait: 300,
      onSuccess: (res) => {
        console.log('res', res);
        setTotal(res.total);
        const list = transformData(res.list);
        setDataList(list);
        const datasetType = filterDatasetTypeList(list);
        setDatasetTypeFillter(datasetType);
      },
    },
  );

  const transformData = (res) => {
    return res.map((item) => {
      const { type } = item;
      let configKey = '';

      switch (type) {
        case 'web':
          configKey = 'webConfig';
          break;
        case 'feishu':
          configKey = 'feishuConfig';
          break;
        default:
          return item;
      }
      const { [configKey]: config, ...rest } = item;
      return { ...rest, ...(config || {}) };
    });
  };

  // const searchTables = (searchText: string) => {
  //   setSearchText(searchText);
  //   searchTablesFn(searchText);
  // };

  // const searchTablesFn = useCallback(
  //   debounce((searchText: string) => {
  //     getTableValue();
  //   }, 500),
  //   [],
  // );

  const getDataset = () => {
    orgService.getDataset({ appId: appId }).then((res) => {
      setTreeData(res.list);
    });
  };

  const onCancelDel = () => {
    setShowDel(false);
  };

  const refresh = () => {
    getTableValue();
    setRefreshSimilarity((prev) => prev + 1);
  };

  const onConfirmDel = (item?) => {
    if (selectedRowKeys && selectedRowKeys.length > 0) {
      // console.log(222222222222, selectedRowKeys);

      const deletePromises = selectedRowKeys.map((_id) => {
        console.log(_id);

        return datasetService.delConnectorList(_id); // 返回每个删除请求的 Promise
      });

      // 使用 Promise.all 并行处理所有删除请求
      Promise.all(deletePromises)
        .then((results) => {
          console.log('所有删除请求的结果：', results);
          setShowDel(false);
          message.success('删除成功');
          refresh(); // 刷新页面或更新状态
          setSelectedRowKeys([]);
        })
        .catch((error) => {
          console.error('删除失败：', error);
          message.error('删除失败');
        });
    } else {
      datasetService.delConnectorList(item._id).then((res) => {
        console.log(res);
        setShowDel(false);
        message.success('删除成功');
        refresh(); // 刷新页面或更新状态
        setSelectedRowKeys([]);
      });
    }
  };

  const onDelete = (item: any) => {
    console.log('删除', item);
    setShowDel(true);
    setOnItem(item);
  };

  const onContinue = (item) => {
    console.log('编辑', item);
    setTitle('编辑');
    setOnItem(item);
    setShowAdd(true);
  };

  const asyncFn = async (arr: string[]) => {
    try {
      await Promise.all(arr.map((_id) => datasetService.taskConnector({ connectorId: _id })));
      message.success('开始同步');
      setSelectedRowKeys([]);

      refresh();
    } catch (error) {
      message.error(`同步失败: ${error.message}`);
    }
  };

  useEffect(() => {
    timeFn();

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, []);

  useEffect(() => {
    dataListRef.current = dataList;
  }, [dataList]);

  const timeFn = () => {
    intervalRef.current = setInterval(() => {
      // const incompleteTasks = dataList.filter((item) => item.progress !== 100);
      const incompleteTasks = dataListRef.current.filter((item) => item.progress !== 100);

      if (incompleteTasks.length === 0) {
        console.log('没有任务');

        return;
      }
      if (incompleteTasks.length > 0) {
        console.log('有任务');
        refresh();
      }
    }, 2000);
  };

  const onSync = async (item) => {
    asyncFn([item._id]);
  };

  const onConfirmAdd = async (item: ItemType) => {
    console.log('提交', item);

    if (item.type === 'api') {
      if (item.datasetCreateType === 'metadata' && item.datasetNameMetadata === '') {
        message.error('请输入需要使用的metadata字段');
        return;
      }
    }

    // const urls = item.urls.split(/[,，]/);
    let urls;
    if (item.urls) {
      if (isArray(item.urls)) {
        urls = item.urls;
      } else {
        // urls = item.urls.split(/[,，]/);

        urls = item.urls
          .trim()
          .split('\n')
          .filter((urlpre) => urlpre.trim() !== '');
      }
    }
    console.log('item.datasetId=========', item);

    const itemdata = {
      type: item.type,
      // urls: urls,
      dbConfig: { link: item.link, sql: item.sql },
      apiConfig: {
        apiKey: item.apiKey,
        apiType: item.apiType,
        resourceType: item.resourceType,
      },
      metaData: {
        appId: appId,
        datasetId: item.datasetId.at(-1),
        tree: item.datasetId,
      },
      ...(item.type === 'web'
        ? {
          webConfig: {
            urls: urls,
            depth: item.depth ? 1 : 0,
          },
        }
        : {}),
      ...(item.type === 'feishu'
        ? {
          feishuConfig: {
            urls: urls,
            feishuAppId: item.feishuAppId,
            feishuAppSecret: item.feishuAppSecret,
            forceSync: item.forceSync,
          },
        }
        : {}),
      cron: item.cron,
      datasetNameMetadata: item.datasetNameMetadata,
      datasetCreateType: item.datasetCreateType,
      name: item.name,
      clockTime: item.clockTime,
      // isdeep: item.isdeep,
    };

    const validateitem = {
      type: item.type,
      urls: urls,
      apiConfig: { apiKey: item.apiKey, apiType: item.apiType },
      dbConfig: { link: item.link, sql: item.sql },
      clockTime: item.clockTime,
      // isdeep: item.isdeep,
      // depth: item.depth ? 1 : 0,
      appId: appId,
      ...(item.type === 'web'
        ? {
          webConfig: {
            urls: urls,
            depth: item.depth ? 1 : 0,
          },
        }
        : {}),
      ...(item.type === 'feishu'
        ? {
          feishuConfig: {
            urls: urls,
            feishuAppId: item.feishuAppId,
            feishuAppSecret: item.feishuAppSecret,
            forceSync: item.forceSync,
          },
        }
        : {}),
    };

    if (item.type == 'database' || item.type == 'api') {
      try {
        const checkRes = await datasetService.validateConnector(validateitem);

        console.log('checkRes===========', checkRes);
        if (checkRes.success === true) {
          if (title == '新增') {
            datasetService.addConnectorList(itemdata).then((res) => {
              console.log(res);
              message.success('提交成功');
              setShowAdd(false);
              refresh();
              setIsErr('');
            });
          } else {
            datasetService.updataConnectorList(onItem?._id, itemdata).then((res) => {
              console.log(res);
              message.success('更新成功');
              setShowAdd(false);
              refresh();
              setIsErr('');
            });
          }
        } else {
          console.log('校验失败');

          setIsErr(item.type);
        }
      } catch (error) {
        console.log('error============', error);

        setIsErr(item.type);
      }
    } else {
      const checkRes = await datasetService.validateConnector(validateitem);
      console.log('checkRes1===========', checkRes);
      if (checkRes.success === true) {
        if (title == '新增') {
          datasetService.addConnectorList(itemdata).then((res) => {
            console.log(res);
            message.success('提交成功');
            setShowAdd(false);
            refresh();
            setIsErr('');
          });
        } else {
          datasetService.updataConnectorList(onItem?._id, itemdata).then((res) => {
            console.log(res);
            message.success('更新成功');
            setShowAdd(false);
            refresh();
            setIsErr('');
          });
        }
      }
    }
  };

  const onCancelAdd = () => {
    setShowAdd(false);
    setIsErr('');
    setOnItem({});
  };

  const addConnector = async () => {
    try {
      const data = await datasetService.addConnectorList({
        page: 1,
        page_size: 10,
        searchText: searchText,
        offset: 0,
        type: '',
      });
      console.log(data.list);
    } catch (error) {
      console.error(error);
    }
  };

  const getData = async () => {
    try {
      const data = await datasetService.getConnectorList({
        page: 1,
        page_size: 10,
        searchText: searchText,
        offset: 0,
        type: '',
      });
      console.log(data.list);

      setConnectorList(data.list);
    } catch (error) {
      console.error(error);
    }
  };

  const timeAgo = (inputTimeStr) => {
    // 将输入的时间字符串转换为Date对象
    const inputTime = new Date(inputTimeStr);

    // 获取当前时间
    const currentTime = new Date();

    // 计算时间差（以毫秒为单位）
    const diffInMillis = currentTime - inputTime;

    if (diffInMillis < 0) {
      return '0分钟前';
    }

    // 转换为分钟、小时和天数
    const minutesDiff = Math.floor(diffInMillis / (1000 * 60));
    const hoursDiff = Math.floor(diffInMillis / (1000 * 60 * 60));
    const daysDiff = Math.floor(diffInMillis / (1000 * 60 * 60 * 24));

    if (daysDiff > 0) {
      return `${daysDiff}天前`;
    } else if (hoursDiff > 0) {
      return `${hoursDiff}小时前`;
    } else if (minutesDiff > 0) {
      return `${minutesDiff}分钟前`;
    } else {
      return '0分钟前'; // 小于1分钟
    }
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ===========', newSelectedRowKeys);

    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    // selections: [
    //   {
    //     key: 'all',
    //     text: (
    //       <div className="flex w-32 items-center justify-between">
    //         <p>{'全部类型'}</p>
    //         <p>({dataList.length})</p>
    //       </div>
    //     ),
    //     onSelect: () => {
    //       let newSelectedRowKeys = dataList.map((row) => row._id);
    //       setSelectedRowKeys(newSelectedRowKeys);
    //       // setFiltType('');
    //     },
    //   },
    //   {
    //     key: 'file',

    //     text: (
    //       <div className="flex w-32 items-center justify-between">
    //         <p>{'文件'}</p>
    //         <p>({dataList.filter((row) => row.type === 'file').length})</p>
    //       </div>
    //     ),
    //     onSelect: () => {
    //       const selectedRows = dataList.filter((row) => {
    //         return row.type === 'file';
    //       });
    //       let newSelectedRowKeys = selectedRows.map((row) => row._id);
    //       setSelectedRowKeys(newSelectedRowKeys);
    //       // setFiltType('file');
    //     },
    //   },
    //   {
    //     key: 'web',
    //     text: (
    //       <div className="flex w-32 items-center justify-between">
    //         <p>{'网页'}</p>
    //         <p>({dataList.filter((row) => row.type === 'web').length})</p>
    //       </div>
    //     ),
    //     onSelect: () => {
    //       const selectedRows = dataList.filter((row) => {
    //         return row.type === 'web';
    //       });
    //       let newSelectedRowKeys = selectedRows.map((row) => row._id);
    //       setSelectedRowKeys(newSelectedRowKeys);
    //       // setFiltType('web');
    //     },
    //   },
    //   {
    //     key: 'api',
    //     text: (
    //       <div className="flex w-32 items-center justify-between">
    //         <p>{'API'}</p>
    //         <p>({dataList.filter((row) => row.type === 'api').length})</p>
    //       </div>
    //     ),
    //     onSelect: () => {
    //       const selectedRows = dataList.filter((row) => {
    //         return row.type === 'api';
    //       });
    //       let newSelectedRowKeys = selectedRows.map((row) => row._id);
    //       setSelectedRowKeys(newSelectedRowKeys);
    //       // setFiltType('api');
    //     },
    //   },
    //   {
    //     key: 'database',
    //     text: (
    //       <div className="flex w-32 items-center justify-between">
    //         <p>{'数据库'}</p>
    //         <p>({dataList.filter((row) => row.type === 'database').length})</p>
    //       </div>
    //     ),
    //     onSelect: () => {
    //       const selectedRows = dataList.filter((row) => {
    //         return row.type === 'database';
    //       });
    //       let newSelectedRowKeys = selectedRows.map((row) => row._id);
    //       setSelectedRowKeys(newSelectedRowKeys);
    //       // setFiltType('database');
    //     },
    //   },
    // ],
    getCheckboxProps: (record: DataType) => ({
      disabled: record.progress != 100 || record.cron !== 'manual', // Column configuration not to be checked
      name: record.name,
    }),
  };

  const handleTableChange = (pagination: any, filters: any) => {
    const typeFilter = filters.type?.[0];

    let filteredData = [] as any;
    if (typeFilter && typeFilter !== 'all' && filters.type?.length) {
      filteredData = dataList.filter((row) => filters.type.includes(row.type));
    } else if (typeFilter && typeFilter === 'all' && filters.type?.length) {
      filteredData = dataList;
    }

    setSelectedRowKeys(filteredData.map((row) => row._id));
  };

  const columns: TableColumnsType<connectorTypeReq> = [
    {
      title: '全部类型',
      dataIndex: 'type',
      width: 200,
      filters: datasetTypeFillter,
      // onFilter: (value, record) => { return value === 'all' ? true : record.type === value; },
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: 200,
      render: (_, record) => (
        <div style={{ overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'Ellipsis' }}>
          {record.name ? record.name : '--'}
        </div>
      ),
    },
    {
      title: '地址',
      dataIndex: 'urls',
      width: 300,

      render: (_, record) => (
        <div>
          {record.type == 'database' && <div>{record.dbConfig.link}</div>}
          {record.type != 'database' && (
            <Ellipsis
              content={
                record.urls.join('\n') // 将分隔符改为换行符
              }
              rows={3}
              expandText={<DownOutlined />}
              collapseText={<UpOutlined />}
              // 添加以下样式（如果组件支持 style 属性）
              style={{ whiteSpace: 'pre-line' }}
            />
          )}
        </div>
      ),
    },
    {
      title: '同步方式',
      dataIndex: 'cron',
      width: 150,
      render: (value) => {
        const obj = {
          manual: '不自动更新',
          everyday: '每天更新',
          every3day: '每三天更新',
          every7day: '每周更新',
        };
        return <span>{value ? obj[value] : '-'}</span>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 150,
      render: (_, record) => (
        <div>
          {record.status == 0 ? (
            record.latestSyncTime ? (
              <div className="text-@success-color">{record.status_cn}</div>
            ) : (
              <div>--</div>
            )
          ) : record.status == 1 ? (
            <div className="text-@success-color">{`同步中...${record.progress}%`}</div>
          ) : (
            <div className="text-@error-color">{record.status_cn}</div>
          )}
        </div>
      ),
    },
    {
      title: '预计剩余时间',
      dataIndex: 'remainingTime',
      width: 300,
      render: (_, record) => (
        <div
          style={{
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'Ellipsis',
          }}
        >
          {record.remainingTime}
        </div>
      ),
    },
    {
      title: '最近同步',
      dataIndex: 'latestSyncTime',
      width: 150,

      render: (_, record) => (
        <div>
          {/* {record.latestSyncTime && dayjs(record.latestSyncTime).format('YYYY-MM-DD HH:mm:ss')} */}
          {record.status != 1 ? (
            record.latestSyncTime ? (
              // getRelativeTimeString(record.latestSyncTime.split('.')[0])
              timeAgo(record.latestSyncTime)
            ) : (
              <div>未同步</div>
            )
          ) : (
            <div style={{ color: '#1BB56B' }}>{`同步中`}</div>
          )}
        </div>
      ),
    },
    {
      title: '操作',
      dataIndex: 'act',
      width: 200,

      render: (_, record) => (
        <div className="flex cursor-pointer items-center gap-2 text-@brand-color">
          <Button
            onClick={() => {
              onSync(record);
            }}
            // className={`${
            //   record.progress != 100 || record.cron !== 'manual'
            //     ? 'text-@brand-color-disabled'
            //     : 'text-@brand-color'
            // }`}
            type="text"
            style={{
              // color: record.progress != 100 || record.cron !== 'manual' ? 'grey' : '#7e5bef',
              cursor:
                record.progress != 100 || record.cron !== 'manual' ? 'not-allowed' : 'pointer',
              background: 'none',
              border: 'none',
              // padding: 0,
              font: 'inherit',
            }}
            disabled={record.progress != 100 || record.cron !== 'manual'}
          >
            <SvgIcon icon="tongbu"></SvgIcon>
            同步
          </Button>
          <Button
            onClick={() => {
              onContinue(record);
            }}
            type="text"
            style={{
              // color: record.progress != 100 ? 'grey' : '#7e5bef',
              cursor: record.progress != 100 ? 'not-allowed' : 'pointer',
              background: 'none',
              border: 'none',
              // padding: 0,
              font: 'inherit',
            }}
            disabled={record.progress != 100}
          >
            <SvgIcon icon="singleedit"></SvgIcon>
            编辑
          </Button>
          <Button
            onClick={() => {
              onDelete(record);
            }}
            type="text"
            danger
            style={{
              // color: record.progress == 100 ? 'grey' : '#7e5bef',
              // cursor: record.progress != 100 ? 'not-allowed' : 'pointer',
              // color: '#7e5bef',
              background: 'none',
              border: 'none',
              // padding: 0,
              font: 'inherit',
            }}
          // disabled={record.progress != 100}
          >
            <SvgIcon icon="deltongbu"></SvgIcon>
            删除
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div className="flex h-full flex-col overflow-hidden bg-[#fff]">
      {/* <div className="flex h-20 items-center justify-between bg-[#FFF] pl-4 pr-4"> */}
      <PagesHeader>
        数据同步
        <TipDesc title='通过内置的"数据连接器"，可以定时更新网页等类型的知识库' className='!my-0' />
      </PagesHeader>
      <div className="flex justify-between px-4 pt-4">
        <Search
          placeholder="请输入内容"
          onChange={(e) => {
            setPage(1);
            setSearchText(e.target.value);
            getTableValue();
          }}
          className=" !rounded-md"
          style={{
            height: '32px',
            width: isPc ? '240px' : '160px',
          }}
        />
        <Button
          style={{
            border: '1px solid #1B6DFA',
            color: '#1B6DFA',
          }}
          className="items-center justify-center"
          icon={<PlusOutlined />}
          onClick={() => {
            setTitle('新增');
            setOnItem({
              type: 'web',
              name: '',
              databaseType: 'mysql',
              link: '',
              cron: 'manual',
              apiKey: '',
              apiType: 'add',
              resourceType: 'web',
              // datasetId: '',
              datasetCreateType: 'manual',
              datasetNameMetadata: '',
              sql: '',
              urls: [],
              isdeep: false,
            });
            setShowAdd(true);
          }}
        >
          <div>新增</div>
        </Button>
      </div>

      <div className="mt-4 h-full pb-4 pl-4 pr-4">
        <Tables<connectorTypeReq>
          columns={columns}
          rowKey="_id"
          scroll={{
            x: 'auto',
          }}
          rowSelection={rowSelection}
          dataSource={dataList}
          paginationProps={paginationConfig}
          expandable={{
            expandedRowRender: ({ child_task_status }) => {
              return (
                <div className="ml-[72px] flex flex-col gap-2">
                  <div className="grid grid-cols-3 gap-2 rounded-sm bg-fill-2 p-2">
                    <div>地址</div>
                    <div>任务状态</div>
                    <div>失败原因</div>
                  </div>
                  {child_task_status?.map((item) => {
                    return (
                      <div className="ml-1 grid grid-cols-3 items-center gap-2">
                        <Ellipsis
                          content={item.task_url}
                          rows={2}
                          expandText={<DownOutlined />}
                          collapseText={<UpOutlined />}
                          // 添加以下样式（如果组件支持 style 属性）
                          style={{ whiteSpace: 'pre-line' }}
                        />
                        <div
                          className={`${item.task_status === 'FAIL'
                            ? 'text-@error-color'
                            : item.task_status === 'WARNING'
                              ? 'text-@warning-color'
                              : 'text-text-5'
                            }`}
                        >
                          {item.task_status_cn}
                        </div>
                        <Ellipsis
                          content={item.task_fail_reason}
                          rows={2}
                          expandText={<DownOutlined />}
                          collapseText={<UpOutlined />}
                          // 添加以下样式（如果组件支持 style 属性）
                          style={{ whiteSpace: 'pre-line' }}
                        />
                      </div>
                    );
                  })}
                </div>
              );
            },
            rowExpandable: (record) => {
              return !!(record.child_task_status && record.child_task_status.length > 0);
            },
          }}
          onChange={handleTableChange}
        />
      </div>

      {selectedRowKeys.length > 0 && (
        <div
          className="animated-div"
          style={{
            position: 'fixed',
            bottom: '5%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: '#474C5F',
            borderRadius: '50px',
          }}
        >
          <Space className="ml-2 mr-2" style={{ height: '45px' }}>
            <Button
              style={{ color: '#fff' }}
              type="text"
              icon={<CloseOutlined />}
              onClick={() => {
                setSelectedRowKeys([]);
                setShowDel(false);
              }}
            />
            <span className="whitespace-nowrap text-nowrap text-xs" style={{ color: '#8E93A4' }}>
              已选 {selectedRowKeys.length} 项
            </span>
            <Splitter />
            {true && (
              <Button
                style={{ color: '#fff' }}
                type="text"
                onClick={() => {
                  // onSync(false);
                  asyncFn(selectedRowKeys);
                }}
              >
                同步
              </Button>
            )}

            <Button style={{ color: '#fff' }} type="text" onClick={onDelete}>
              删除
            </Button>
          </Space>
        </div>
      )}

      <ConnectorDeleteModal
        visible={showDel}
        onCancel={onCancelDel}
        onConfirm={onConfirmDel}
        onItem={onItem}
      />

      <ConnectorAddModal
        visible={showAdd}
        onCancel={onCancelAdd}
        onConfirm={onConfirmAdd}
        onItem={onItem}
        title={title}
        isErr={isErr}
        treeData={treeData}
      />
    </div>
  );
};

export default Connector;
